package com.wujilee.wujileenetty.demos.web.bioService;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author liwuji
 * @date 2024/7/29
 * @desc
 **/
public class Service {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(6666);
        ExecutorService executorService = Executors.newCachedThreadPool();
        while (true){
            Socket accept = serverSocket.accept();
            System.out.println("产生了新的连接");
            executorService.execute(()-> handleConntion(accept));
        }
    }
    public static void  handleConntion(Socket socket){
        try {
            System.out.println("建立连接");
            InetAddress inetAddress = socket.getInetAddress();
            System.out.println("inetAddress :" +inetAddress);
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("hello".getBytes());
            byte[] arr = new byte[1024];
            InputStream inputStream = socket.getInputStream();
            int count = 0;
            while (true){
                int read = inputStream.read(arr);
                if(read != -1){
                    System.out.println(new String(arr,0,read));
                }
                count++;
                if(count >= 4){
                    throw  new RuntimeException("服务器主动关闭连接");
                }

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            System.out.println("关闭连接");
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }


    }
}
